/*引入axios*/
import axios from 'axios'
import router from '../router/index.js'
import ElementUI from 'element-ui';
import {
	getVersion
} from '../utils/version.js'

let baseUrl; // 不同环境下的地址
let debug; // 是否开启debug模式
//node中的环境变量process.env,也就是我们新增开发、生产的配置文件
console.log(process.env.NODE_ENV);
if (process.env.NODE_ENV === "development") {
	baseUrl = "/api";
	debug = true;
} else {
	baseUrl = "123.com.cn"
	debug = false;
}

const request = axios.create({
	baseURL: baseUrl, // 基础路径,将统一的部分全部封装
	timeout: 4000,
	withCredentials: true, // 表示请求可以携带cookie
	headers: {
		"Content-Type": "application/x-www-form-urlencoded"
	}
})
export function get(url, params) {
	return request.get(url, {
		params: params
	});
}
export function post(url, params) {
	return request.post(url, params);
}
export function postJson(url, data) {
	return request.post(url, data, {
		headers: {
			"Content-Type": "application/json"
		}
	})
}

// 在请求前添加my-version请求头
request.interceptors.request.use((config) => {
	config.headers["my-version"] = getVersion(); //添加header
	return config;
})

// 解包返回response
request.interceptors.response.use((response) => {
	if (debug) {
		if (response.config.method == "get") console.log("请求地址：", response.config.method, "请求url：", response
			.request.responseURL, "返回的response:", res);
		else console.log("请求地址：", response.config.method, "请求url：", response.request.responseURL, "请求参数：",
			response.config.data, "返回的response:", res);
	}
	var res = response.data;
	res.headers = response.headers;

	console.log("简化后的response", res);
	// 获取code值
	switch (res.code) {
		case 0:
			if (debug) ElementUI.Message.success({
				message: "调试信息：" + res.message,
				duration: 800,
			});
			break;
		case 500:
			if (debug) ElementUI.Message.error({
				message: "调试信息：" + res.message,
				duration: 800,
			});
			break;
		case 2:
			ElementUI.Message.warning("您还未登录")
			setTimeout(() => {
				if (router.currentRoute.path != res.location) { //判断是否跳向自身
					router.push({
						path: newResponse.location
					});
				}
			}, 800);
			break;
	}
	return res;
})